package net.gxf.common.util;

import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.HashMap;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * 用于加载Key=Value格式的配置文件工具，返回一个HashMap
 * 
 * # 表示不加载此行 ，注释采用这种形式，不实现多行注释
 * 
 * 支持加载文件名路径，当只指定文件名称时，该文件需放在classPath下面
 * 
 * @author: maybe
 * 
 */
public class ConfigLoader {
	static final Logger logger = LoggerFactory.getLogger(ConfigLoader.class);
	private static final int MAX_BLANK_NUMBER = 50;// 如果开始空行大于50行或连续空白50行，不加载后面的内容

	public static HashMap<String, String> loadConfig(String pathOrFileName) {
		logger.info("loading config file from path: {}",pathOrFileName);
		HashMap<String, String> configMap = new HashMap<String, String>();
		try {
			InputStreamReader inputStreamReader;
			if (pathOrFileName.contains(":")) {
				inputStreamReader = new InputStreamReader(new FileInputStream(pathOrFileName));
			} else {
				inputStreamReader = new InputStreamReader(ResourceLoader.getResourceAsStream(pathOrFileName));
			}
			BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
			int count = 0;
			String readLine;
			readLine = bufferedReader.readLine();
			while (true) {
				if (readLine == null || readLine.length() == 0) {
					readLine = bufferedReader.readLine();
					if (count++ > MAX_BLANK_NUMBER)
						break;
					continue;
				}
				if (readLine.startsWith("#")) {
					readLine = bufferedReader.readLine();
					continue;// 不解析注释的行
				}
				int index = readLine.indexOf("=");
				String key = readLine.substring(0, index);
				String value = readLine.substring(index + 1);
				configMap.put(key.trim(), value.trim());
				readLine = bufferedReader.readLine();
				count = 0;
			}
		} catch (IOException e) {
			logger.info("loading failed ...");
			e.printStackTrace();
		}
		return configMap;
	}
}
